﻿using FreeDream.Common;
using log4net;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Infrastructure
{
    /// <summary>
    /// 生成种子数据中间件服务
    /// </summary>
    public static class SeedDataMiddleware
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(SeedDataMiddleware));


        //public static void UseSeedDataMiddle(this WebApplicationBuilder app, MySugarContext myContext, string webRootPath)
        public static void UseSeedDataMiddle(this WebApplication app, string webRootPath)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            try
            {
                if (AppSettings.App("AppSettings", "SeedDBEnabled").ObjToBool() || AppSettings.App("AppSettings", "SeedDBDataEnabled").ObjToBool())
                {
                    using var scope = app.Services.CreateScope();
                    var services = scope.ServiceProvider;

                    //var provider = app.Services.GetService<MySugarContext>();

                    //try
                    //{
                    //    var context = services.GetRequiredService<MySugarContext>();
                    //    DBSeed.SeedAsync(context, webRootPath).Wait();
                    //}
                    //catch (Exception ex)
                    //{
                    //    throw new Exception($"an error occurred migrating the db: {ex.Message}");
                    //}
                    ////((IServiceProvider)app.Services).GetService(typeof(Dn.Common.Seed.MySugarContext))
                    ////DBSeed.SeedAsync(new Dn.Common.Seed.MySugarContext(), webRootPath).Wait();
                    ////DBSeed.SeedAsync(myContext, webRootPath).Wait();
                }
            }
            catch (Exception e)
            {
                Log.Error($"Error occured seeding the Database.\n{e.Message}");
                throw;
            }
        }
    }
}
